
import React,{useState,useEffect,useRef} from 'react'
//import usePiostion from '../hooks/usePositon'
type LikeButtonFn = (num:number) => boolean
interface ILikeButton {
  setage?:LikeButtonFn
}
 const LikeButton:React.FC<ILikeButton> = (props:ILikeButton) => {
  //rending 的时候 都是一个不同的值（修改它的值重新 rending)
  const [like,setLike] = useState(0)
  const [on,setOn] = useState(true)
  const [obj,setObj] = useState({lienum:2,sex:'5'})
  //无论何时 都始终保持同一个值 同一个引用(修改它的值是不会重新 rending)
  const likenum = useRef(0)
  const didMontRef = useRef(false)
  const inputDomRef = useRef<HTMLInputElement>(null)

  //const position = usePiostion()
  //like reding后会执行
  useEffect(()=>{
    console.log("like变化 更新执行")
    document.title = `${like}`
  },[like])
  //任何值变化 reding 都会执行
  useEffect(()=>{
    if(didMontRef && didMontRef.current){
      console.log("this is updated")
      console.log(inputDomRef)
    }else{
      //第一次reding 完
      console.log("第一次reding 完成")
      console.log(inputDomRef)
      inputDomRef.current?.focus()
      didMontRef.current = true
    }
  })
  function setFn(){
    setOn(!on)
    setObj({...obj,lienum:obj.lienum+1})
    props.setage && props.setage(1)
  }
  function clickfn(){
    setTimeout(()=>{
      alert(likenum.current)
      alert(like)
    },3000)
  }
  function inputOnchange(ev: React.ChangeEvent<HTMLInputElement>){
    ev.preventDefault()
    console.log(ev.target.value)
  }
  return (
    <>
    <input type="text" ref={inputDomRef} onChange={(ev)=>{inputOnchange(ev)}}></input>
    <button onClick = {(e)=>{
      e.nativeEvent.stopImmediatePropagation()
      setLike(like + 1)
      likenum.current ++
     }
    }>
      {like} 👍
    </button>

    <button onClick = {clickfn}>
      alert
    </button>

    <button onClick = {setFn}>
      {on ? 'on' : 'off'} {obj.lienum}
    </button>

    {/* <h2>x:{position.x}  y:{position.y}</h2> */}
    </>
  )
}
export default LikeButton
